import requests
import time
import os
import io
from Panda.Core.Utils import write_yaml, read_yaml
from Panda.Core.Logme import logger


class Client:
    def __init__(self, app_id, app_secret):
        self.app_id = app_id
        self.app_secret = app_secret
        self.body = {
            "grant_type": "client_credential",
            "appid": self.app_id,
            "secret": self.app_secret,
        }
        self.token = self.check_token()

    def get_access_token(self):
        url = "https://api.weixin.qq.com/cgi-bin/token"
        ret = requests.get(url, params=self.body)
        if "access_token" not in ret.json() or "expires_in" not in ret.json():
            raise Exception(ret.text)
        token_dict = {
            "access_token": ret.json()["access_token"],
            "expires_time": int(time.time()) + 7200,
            "expires_in": 7200,
        }
        write_yaml(token_dict, f"token.yaml")
        return ret.json()

    def check_token(self):
        if not os.path.exists("token.yaml"):
            ret = self.get_access_token()
            return ret["access_token"]
        else:
            token_dict = read_yaml("token.yaml")
            now_time = int(time.time())
            if now_time < token_dict["expires_time"]:
                token_dict["expires_in"] = token_dict["expires_time"] - now_time
                write_yaml(token_dict, f"token.yaml")
                return token_dict["access_token"]
            else:
                logger.info("Token is invalid or expired. (refresh)")
                ret = self.get_access_token()
                return ret["access_token"]

    @classmethod
    def prepare_file(cls, path):
        """准备上传文件信息：文件名称、文件大小、二进制"""
        if not os.path.exists(path):
            logger.error(f"文件不存在：{path}")  # 如果文件不存在则真
            return "", 0, None
        else:
            with open(path, "rb") as f:
                file_ = f.read()
        return os.path.basename(path), len(file_), io.BytesIO(file_)

    def upload_file(self, path):
        """无需附件模块"""
        filename, length, content = self.prepare_file(path)
        headers = {"Content-Type": "multipart/form-data"}
        params = {"access_token": self.check_token()}
        files = {
            "filename": (None, filename),
            "filelength": (None, length),
            "media": (filename, content, "application/octet-stream"),
        }
        url = "https://api.weixin.qq.com/cgi-bin/material/add_material"
        response = requests.post(url, headers=headers, files=files, params=params)
        logger.info(response.json())
        return response.json().get("media_id", "")


if __name__ == "__main__":
    app_secret = "638c985ec13f9fba369ecfa03e4137cf"
    app_id = "wx38dfd6875798b877"

    client = Client(app_id, app_secret)
    # print(client.check_token())
    # print(read_yaml("token.yaml"))
    client.upload_file(r"D:\Myprog\杨晓林.png")
